import { filter } from '../config'

/**
 * 默认数据值
 */
const defaultValues = {
  'tasks': [{}],
  'mileStones': []
}

/**
 * 将数据同步到localStorage
 * @description 当过滤开启时不进行同步
 */
export function syncLocal() {
  // 过滤开启时不同步数据
  if (filter) return
  
  Object.keys(defaultValues).forEach(key => {
    const lastLocalStorage = localStorage.getItem(key)
    try {
      localStorage.setItem(key, JSON.stringify(window[key]))
    } catch (error) {
      console.error('同步到localStorage失败:', error)
      // 恢复之前的数据
      localStorage.setItem(key, lastLocalStorage)
    }
  })
}

/**
 * 从localStorage获取数据
 * @param {string} key - 数据键名，默认为'tasks'
 * @returns {Array} 数据数组
 */
export function getLocal(key = 'tasks') {
  try {
    const stored = localStorage.getItem(key)
    return stored ? JSON.parse(stored) : defaultValues[key]
  } catch (error) {
    console.error('从localStorage获取数据失败:', error)
    return defaultValues[key]
  }
}

/**
 * 保存数据到localStorage
 * @param {string} view - 视图名称
 */
function saveToLocal(view) {
  Object.keys(defaultValues).forEach(key => {
    const lastLocalStorage = localStorage.getItem(key)
    try {
      localStorage.setItem(key, JSON.stringify(window[key]))
    } catch (error) {
      console.error('保存到localStorage失败:', error)
      localStorage.setItem(key, lastLocalStorage)
    }
  })
}

// 将函数挂载到全局window对象
window.syncLocal = syncLocal
window.saveToLocal = saveToLocal 